function basePath() {
    var curWwwPath = window.document.location.href;
    var pathName = window.document.location.pathname;
    var pos = curWwwPath.indexOf(pathName);
    var localhostPath = curWwwPath.substring(0, pos);
    var projectName = pathName.substring(0, pathName.substr(1).indexOf('/') + 1);
    return (localhostPath + projectName);
}

loading();

var page = 1;
var page_item_num = 0;
var item_num = 10;
var max_page_num = 0;
var updateTime = true;
var addTime = true;

$(function () {
    $('[data-toggle="tooltip"]').tooltip();

    editor = CKEDITOR.replace('enterpriseText');
    newEditor = CKEDITOR.replace('newEnterpriseText');

    $(".selectpicker").selectpicker({
        noneSelectedText: '请选择',
        style: 'btn-default'
    });

    $("#enterpriseStime").datetimepicker({
        language: 'zh',
        format: 'yyyy-mm-dd hh:ii:ss',
        language: 'zh-CN',
        autoclose: true,//选中自动关闭
        initialDate: new Date(),
        startDate: new Date(),
        todayBtn: true,//显示今日按钮
        pickerPosition: 'bottom-right'
    }).change(function () {
        $("#enterpriseEtime").datetimepicker("setStartDate", $("#stime").val());
        validatorTime("#stime", '#enterpriseStime', '#sTimeSmall', addTime);
    });

    $("#enterpriseEtime").datetimepicker({
        language: 'zh',
        format: 'yyyy-mm-dd hh:ii:ss ',
        language: 'zh-CN',
        autoclose: true,//选中自动关闭
        initialDate: new Date(),
        startDate: new Date(),
        todayBtn: true,//显示今日按钮
        pickerPosition: 'bottom-right'
    }).change(function () {
        $("#enterpriseStime").datetimepicker("setEndDate", $("#etime").val())
        validatorTime("#etime", '#enterpriseEtime', '#eTimeSmall', addTime);

    });

    $("#newEnterpriseStime").datetimepicker({
        language: 'zh',
        format: 'yyyy-mm-dd hh:ii:ss',
        language: 'zh-CN',
        autoclose: true,//选中自动关闭
        initialDate: new Date(),
        startDate: new Date(),
        todayBtn: true,//显示今日按钮
        pickerPosition: 'bottom-right'
    }).change(function () {
        $("#newEnterpriseEtime").datetimepicker("setStartDate", $("#newstime").val())
        validatorTime("#newstime", '#newEnterpriseStime', '#newSTimeSmall', updateTime);
    });

    $("#newEnterpriseEtime").datetimepicker({
        language: 'zh',
        format: 'yyyy-mm-dd hh:ii:ss ',
        language: 'zh-CN',
        autoclose: true,//选中自动关闭
        startDate: new Date(),
        todayBtn: true,//显示今日按钮
        pickerPosition: 'bottom-right'
    }).change(function () {
        $("#newEnterpriseStime").datetimepicker("setEndDate", $("#newetime").val())
        validatorTime("#newetime", '#newEnterpriseEtime', '#newETimeSmall', updateTime);

    });

    getPosts();
    getAllProvince();
    getEnterprises(page);
    validatorU();
    validatorA();
    validatorSearch();
    $("#add_enterprise_btn").click(function () {
        addEnterprise();
    });
    $("#update_enterprise_btn").click(function () {
        updateEnterprise();
    });

    $("#list_btn").click(function () {
        var span_value = $("#list_span").html();
        if (span_value == "查看过期企业") {
            getInvalidEnterprises(1);
            $("#list_btn").removeClass();
            $("#list_btn").addClass("btn btn-sm btn-info");
            $("#list_span").html("查看报名企业");
        } else {
            getEnterprises(1);
            $("#list_btn").removeClass();
            $("#list_btn").addClass("btn btn-sm btn-primary");
            $("#list_span").html("查看过期企业");
        }
    });


});


function validatorTime(id1, id2, id3, name) {
    if ($(id1).val() == "") {
        var group = $(id2).parent().parent();
        group.removeClass("has-success");
        group.addClass("has-error");
        $(id3).css('display', '');
        name = false;
    } else {
        var group = $(id2).parent().parent();
        group.removeClass("has-error");
        group.addClass("has-success");
        $(id3).css('display', 'none');
        name = true;
    }
}
function validatorSearch() {
    $('#search_form').bootstrapValidator({
        message: 'is not valid',
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
            ep_name: {
                message: 'this is not valid',
                validators: {
                    stringLength: {
                        max: 30,
                        message: '企业名长度不能过长'
                    }
                }
            }
        }
    });
}
function validatorU() {
    $('#updateForm').bootstrapValidator({
        message: 'is not valid',
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
            newEnterpriseName: {
                message: 'this is not valid',
                validators: {
                    notEmpty: {
                        message: '企业名不能为空'
                    },
                    stringLength: {
                        max: 30,
                        message: '企业名最大长度为30'
                    }
                }
            },
            newEnterpriseStime: {
                message: 'this is not valid',
                validators: {
                    notEmpty: {
                        message: '起始报名时间不能为空'
                    }
                }
            },
            newetime: {
                message: 'this is not valid',
                validators: {
                    notEmpty: {
                        message: '结束报名时间不能为空'
                    }
                }
            }
        }
    });
}

function validatorA() {
    $('#addForm').bootstrapValidator({
        message: 'is not valid',
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
            enterpriseName1: {
                message: 'this is not valid',
                validators: {
                    notEmpty: {
                        message: '企业名不能为空'
                    },
                    stringLength: {
                        max: 30,
                        message: '企业名最大长度为30'
                    }
                }
            },
            stime: {
                message: 'this is not valid',
                validators: {
                    notEmpty: {
                        message: '起始报名时间不能为空'
                    }
                }
            },
            etime: {
                message: 'this is not valid',
                validators: {
                    notEmpty: {
                        message: '结束报名时间不能为空'
                    }
                }
            }
        }
    });
}


function getPosts() {
    var url = basePath() + "/ep/post/post_all.do";
    var args = {};
    $.get(url, args, function (data) {
        if (data.status == 0) {
            var posts = data.data;
            for (var i = 0; i < posts.length; i++) {
                $("#ep_post").append("<option value='" + posts[i].id + "'>" + posts[i].name + "</option>>");
            }
        }
    }, "json");
}


function getEnterprises(pageNum) {
    var posts = $("#ep_post").val();
    var epName = $("#ep_name").val();
    var condition = $("#ep_condition").val();
    $.ajax({
        url: basePath() + '/ep/manager/all_enterprise.do',
        type: 'POST',
        async: 'true',
        data: {
            "pageNum": pageNum,
            "pageSize": item_num,
            "epName": epName,
            "post": posts,
            "condition": condition
        },
        dataType: 'json',
        success: function (data) {
            removeLoading();
            var pageResult = data.data;
            var item = data.data.list;
            page_item_num = item.length;
            max_page_num = pageResult.pages;
            page = setPage(pageResult.pageNum, pageResult.pages, "getEnterprises");
            $("#result").html("");

            for (var i = 0; i < item.length; i++) {
                var temp = $("#m_template").clone();
                temp.attr("id", item[i].id);
                temp.removeAttr("style");
                temp.find(".ep_num").html(pageResult.pageSize * (pageResult.pageNum - 1) + 1 + i);
                temp.find(".ep_name").html(item[i].name);
                temp.find(".ep_stime").html(item[i].sTime);
                temp.find(".ep_etime").html(item[i].eTime);
                if (item[i].type == 0) {
                    temp.find(".ep_type").html("全部");
                }
                if (item[i].type == 1) {
                    temp.find(".ep_type").html("开发");
                }
                if (item[i].type == 2) {
                    temp.find(".ep_type").html("测试");
                }

                if (item[i].category == 0) {
                    temp.find(".ep_category").html("招聘");
                }
                if (item[i].category == 1) {
                    temp.find(".ep_category").html("定制");
                }

                var info = "<h3>正文</h3>" + item[i].text + "<br><h3>岗位需求</h3><br>";
                for (var j = 0; j < item[i].posts.length; j++) {
                    info += item[i].posts[j].name + "<br>";
                }

                temp.find(".ep_category").before("<input type='hidden' value='" + info + "'/>");
                var eStime = new Date(Date.parse(item[i].eTime.replace(/-/g,"/")));
                var uenterprise;
                var output;
                if (eStime > new Date()) {
                    //修改按钮组装
                    uenterprise = "<button type='button'  class='btn btn-primary btn-xs btn-warning' onclick='toUpdate(this," + item[i].id + ");' ><span class='glyphicon glyphicon-edit' aria-hidden='true'></span><span style='margin: 0px 8px;'>修改</span></button>"
                    //导出按钮组装
                    output = "<button type='button' disabled='disabled' class='btn btn-danger btn-xs' onclick='output(" + item[i].id + ");' ><span class='glyphicon glyphicon-download' aria-hidden='true'></span><span style='margin: 0px 8px;'>导出</span></button>"
                } else {
                    output = "<button type='button'  class='btn btn-danger btn-xs' onclick='output(" + item[i].id + ");' ><span class='glyphicon glyphicon-download' aria-hidden='true'></span><span style='margin: 0px 8px;'>导出</span></button>"
                    uenterprise = "<button type='button'  disabled='disabled' class='btn btn-primary btn-xs btn-warning' onclick='toUpdate(this," + item[i].id + ");' ><span class='glyphicon glyphicon-edit' aria-hidden='true'></span><span style='margin: 0px 8px;'>修改</span></button>"
                }
                temp.find(".ep_update").append(uenterprise);
                temp.find(".ep_output").append(output);
                //正文按钮组装
                var enterpriseInfo = "<button type='button'  class='btn btn-primary btn-xs' onclick='toInfo(this);' ><span class='glyphicon glyphicon-eye-open' aria-hidden='true'></span><span style='margin: 0px 8px;'>查看</span></button>"
                temp.find(".ep_info").append(enterpriseInfo);
                $("#result").append(temp);
            }
        }
    })
};


function output(enterpriseId) {

    var dialog = bootbox.dialog({
        title: '请稍候',
        message: '<i class="icon-spinner icon-spin icon-2x pull-left"></i> 导出中...</p>'
    });

    var name = $("tr[id='"+enterpriseId+"']").find('.ep_name').html();
    var url = basePath() + "/ep/out/output_sign.do?enterpriseId=" + enterpriseId;
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);        // 也可以使用POST方式，根据接口
    xhr.responseType = "blob";    // 返回类型blob
    // 定义请求完成的处理函数，请求前也可以增加加载框/禁用下载按钮逻辑
    xhr.onload = function () {
        // 请求完成
        if (this.status === 200) {
            // 返回200
            var blob = this.response;
            var reader = new FileReader();
            reader.readAsDataURL(blob);    // 转换为base64，可以直接放入a表情href
            reader.onload = function (e) {
                // 转换完成，创建一个a标签用于下载
                var a = document.createElement('a');
                a.download = name+"报名表.xlsx";
                a.href = e.target.result;
                $("body").append(a);    // 修复firefox中无法触发click
                a.click();
                $(a).remove();
                dialog.find('.modal-title').html('完成');
                dialog.find('.modal-body').html("导出成功");
                dialog.find('.modal-body').after("<div class=\"modal-footer\"><button data-bb-handler=\"ok\" type=\"button\" class=\"btn btn-primary\">OK</button></div>");

            }
        }
    };
    // 发送ajax请求
    xhr.send();
}


function toInfo(temp) {
    var text = $(temp).parent().parent().children(":input").val();
    $("#enterpriseTextInfo").html(text);
    $("#enterpriseInfo").modal("show");
}

//todo
function getDirections(node) {
    var url = basePath() + "/ep/manager/get_all_directions.do";
    var data = "";
    $.get(url, data, function (data) {
        if (data.status == 0) {
            var direction = data.data;
            $(node).append("<option value='0'>全部</option>");
            for (var i = 0; i < direction.length; i++) {
                if (direction[i].id > 0 && direction[i].id < 3) {
                    $(node).append("<option value='" + direction[i].id + "'>" + direction[i].name + "</option>");
                }
            }
        } else {
            bootbox.alert(data.msg);
        }
    }, "JSON");

}

function toUpdate(updateButton, enterpriseId) {
    $(updateButton).attr("disabled", "disabled");
    $("#newEnterprisePost").children().remove();
    getDirections("#newEnterpriseType");

    var url = basePath() + "/ep/manager/toupdate_enterprise.do";
    var data = {"enterpriseId": enterpriseId};
    $.get(url, data, function (data) {
        if (data.status == 0) {

            $("#newEnterpriseName").val(data.data.enterprise.name);
            $("#newEnterpriseNameId").val(enterpriseId);
            $("#newstime").val(data.data.enterprise.sTime);
            $("#newEnterpriseEtime").datetimepicker("setStartDate", data.data.enterprise.sTime)
            $("#newetime").val(data.data.enterprise.eTime);
            $("#newEnterpriseStime").datetimepicker("setEndDate", data.data.enterprise.eTime)
            for (var i = 0; i < data.data.posts.length; i++) {
                $("#newEnterprisePost").append("<option value=" + data.data.posts[i].id + " >" + data.data.posts[i].name + "</option>");
            }
            //多选下拉框刷新
            $('#newEnterprisePost').selectpicker("refresh");
            //回显
            var arr = new Array();
            for (var j = 0; j < data.data.enterprise.posts.length; j++) {
                arr[j] = data.data.enterprise.posts[j].id;
            }
            $('#newEnterprisePost').selectpicker("val", arr);
            if (data.data.enterprise.position != null) {
//                    回显位置
                echo(data.data.enterprise.position);
            }
            $("newCity option[value=" + data.data.position + "]").prop("selected", true);

            $("#newEnterpriseCategory option[value=" + data.data.enterprise.category + "]").attr("selected", true);
            $("#newEnterpriseType option[value=" + data.data.enterprise.type + "]").attr("selected", true);
            newEditor.setData(data.data.enterprise.text);
            $('#changEnterprise').modal({backdrop: 'static', keyboard: false});
            $(updateButton).removeAttr("disabled");
        } else {
            bootbox.alert(data.msg, function () {

            });
        }
    }, "JSON");
}


//todo
function echo(positionId) {
    $.ajax({
        url: basePath() + "/ep/manager/get_position.do",
        type: 'post',
        async: false,
        data: {"positionId": positionId},
        dataType: 'json',
        success: function (data) {
            if (data.success) {
                $("#newProvince option[value = '" + data.data.province + "'] ").prop("selected", true);
                getCity2(data.data.province);
                $("#newCity option:contains('" + data.data.city + "') ").prop("selected", true);
            } else {
            }
        }
    });
}

function getCity2(province) {
    $.ajax({
        url: basePath() + '/ep/manager/get_city.do',
        type: 'post',
        async: false,
        data: {'province': province},
        dataType: 'json',
        success: function (res) {
            //移除原有的数据
            $('#newCity').empty();
            if (res.success) {
                $.each(res.data, function (index, item) {
                    var op = "<option value='" + item.id + "'>" + item.city + "</option>";
                    $('#newCity').append(op);
                });
            } else {
            }
        }
    });
}

function toAdd() {
    $("#enterprisePost").children().remove();
    var url = basePath() + "/ep/post/post_all.do";
    var data = "";
    $.get(url, data, function (data) {
        if (data.status == 0) {
            var items = data.data;
            for (var i = 0; i < items.length; i++) {
                $("#enterprisePost").append("<option value=" + items[i].id + ">" + items[i].name + "</option>");
            }
            $('#addEnterprise').modal({backdrop: 'static', keyboard: false});
            $('#enterprisePost').selectpicker("refresh");
        } else {
            bootbox.alert(data.msg, function () {

            });
        }
    }, "JSON");

    getDirections("#enterpriseType");


}

function updateEnterprise() {
    // 提交前先主动验证表单
    var bv = $("#updateForm").data('bootstrapValidator');
    bv.validate();
    if (!bv.isValid()) {
        return;
    }

    if (updateTime == false) {
        return;
    }
    var newEnterprisePostIds = $('#newEnterprisePost').val();
    if (newEnterprisePostIds == null) {
        bootbox.alert("岗位至少选择一个");
        $('#changEnterprise').css('overflow-x', 'hidden');
        $('#changEnterprise').css('overflow-y', 'auto');
        return;
    }

    var url = basePath() + "/ep/manager/update_enterprise.do";
    var id = $("#newEnterpriseNameId").val();
    var newEnterprisename = $("#newEnterpriseName").val();
    var newEnterpriseStime = $("#newstime").val();
    var newEnterpriseEtime = $("#newetime").val();
    var newEnterprisePost = $("#newEnterprisePost").val().toString();
    var newEnterpriseCategory = $("#newEnterpriseCategory").val();
    var newEnterpriseType = $("#newEnterpriseType").val();
    var newEnterpriseText = newEditor.getData();
    var newEnterprisePosition = $("#newCity").val();
    var data = {
        "id": id,
        "name": newEnterprisename,
        "text": newEnterpriseText,
        "sTime": newEnterpriseStime,
        "eTime": newEnterpriseEtime,
        "category": newEnterpriseCategory,
        "type": newEnterpriseType,
        "position": newEnterprisePosition,
        "postIds": newEnterprisePost
    };
    $.post(url, data, function (data) {
        if (data.status == 0) {
            clearUpdateModel();
            getEnterprises(page);
            bootbox.alert(data.msg);
        } else {
            bootbox.alert(data.msg);
        }
    }, "JSON");
};

function addEnterprise() {

    // 提交前先主动验证表单
    var bv = $("#addForm").data('bootstrapValidator');
    bv.validate();
    if (!bv.isValid()) {
        return;
    }

    if (addTime == false) {
        return;
    }

    var enterprisePostIds = $('#enterprisePost').val();
    if (enterprisePostIds == null) {
        bootbox.alert("岗位至少选择一个");
        $('#addEnterprise').css('overflow-x', 'hidden');
        $('#addEnterprise').css('overflow-y', 'auto');
        return;
    }
    var enterprisename = $("#enterpriseName1").val();
    var enterpriseStime = $("#stime").val();
    if (enterpriseStime == "") {
        validatorTime("#stime", '#enterpriseStime', '#sTimeSmall', addTime);
        return;
    } else {
        validatorTime("#stime", '#enterpriseStime', '#sTimeSmall', addTime);
    }
    var enterpriseEtime = $("#etime").val();
    if (enterpriseEtime == "") {
        validatorTime("#etime", '#enterpriseEtime', '#eTimeSmall', addTime);
        return;
    } else {
        validatorTime("#etime", '#enterpriseEtime', '#eTimeSmall', addTime);
    }
    var enterprisePost = $("#enterprisePost").val().toString();
    var enterpriseCategory = $("#enterpriseCategory").val();
    var enterpriseType = $("#enterpriseType").val();
    var enterpriseText = editor.getData();
    var enterprisePosition = $("#city").val();

    $.ajax({
        url: basePath() + "/ep/manager/add_enterprise.do",
        type: "post",
        async: "true",
        data: {
            "name": enterprisename,
            "text": enterpriseText,
            "sTime": enterpriseStime,
            "eTime": enterpriseEtime,
            "category": enterpriseCategory,
            "type": enterpriseType,
            "position": enterprisePosition,
            "postIds": enterprisePost
        },
        dataType: "json",
        success: function (data) {
            console.info(data);
            if (data.status == 0) {
                clearAddModel();
                bootbox.alert("添加成功");
                if (page_item_num == item_num) {
                    getEnterprises(max_page_num);
                } else {
                    getEnterprises(page);
                }
            } else {
                bootbox.alert(data.msg);
            }
        }
    });

}

//to
function getAllProvince() {
    $.ajax({
        url: basePath() + '/ep/manager/get_all_province.do',
        dataType: 'json',
        async: false,
        success: function (res) {
            if (res.success) {
                $.each(res.data, function (index, item) {
                    var op = "<option value='" + item + "'>" + item + "</option>";
                    $('#province').append(op);
                    $('#newProvince').append(op);
                });
            }
        }
    });
}

//to
function getCity1() {
    var province = $('#province').val();

    $.ajax({
        url: basePath() + '/ep/manager/get_city.do',
        type: 'post',
        async: false,
        data: {'province': province},
        dataType: 'json',
        success: function (res) {

            //移除原有的数据
            $('#city').empty();

            if (res.success) {
                $.each(res.data, function (index, item) {
                    var op = "<option value='" + item.id + "'>" + item.city + "</option>";
                    $('#city').append(op);
                });
            } else {

            }
        }

    });
}

//to
function getCity() {
    var province = $('#newProvince').val();

    $.ajax({
        url: basePath() + '/ep/manager/get_city.do',
        type: 'post',
        async: false,
        data: {'province': province},
        dataType: 'json',
        success: function (res) {

            //移除原有的数据
            $('#newCity').empty();

            if (res.success) {
                $.each(res.data, function (index, item) {
                    var op = "<option value='" + item.id + "'>" + item.city + "</option>";
                    $('#newCity').append(op);
                });
            } else {

            }
        }

    });
}

function clearUpdateModel() {
    $("#newEnterpriseStime").datetimepicker("setEndDate", "2100-01-01 00:00")
    $("#newEnterpriseEtime").datetimepicker("setStartDate", new Date());
    $('#changEnterprise').modal('hide');
    $("#newEnterpriseName").val("");
    $("#newstime").val("");
    $("#newetime").val("");
    $("#newEnterprisePost").children().remove();
    $("#newEnterpriseType").children().remove();
    $("#newCity").children().remove();
    $("#newPosition").children().remove();

    newEditor.setData("");
    $('#updateForm').data('bootstrapValidator').destroy();
    $('#updateForm').data('bootstrapValidator', null);
    $("form[id='updateForm'] > div").addClass('has-success');

    validatorU();
}

function clearAddModel() {
    $("#enterpriseStime").datetimepicker("setEndDate", "2100-01-01 00:00")
    $("#enterpriseEtime").datetimepicker("setStartDate", new Date());
    $('#addEnterprise').modal('hide');
    $('#enterpriseName1').val("");
    $("#stime").val("");
    $("#etime").val("");
    $("#enterpriseType").children().remove();
    editor.setData("");

    $('#addForm').data('bootstrapValidator').destroy();
    $('#addForm').data('bootstrapValidator', null);
    $("form[id='addForm'] > div").addClass('has-success');
    validatorA();
}

function toUpload() {

    var dialog = bootbox.dialog({
        title: '请稍候',
        message: '<i class="icon-spinner icon-spin icon-2x pull-left"></i> 导入中...</p>'
    });

    $('#uploadForm').ajaxSubmit({
        url: basePath() + '/ep/input/upload_sign.do',
        type: 'post',
        async: true,
        cache: false,
        contentType: false,
        processData: false,
        dataType: 'json',
        success: function (res) {
            if (res.success) {
                dialog.find('.modal-title').html('完成');
                dialog.find('.modal-body').html(res.msg);
                dialog.find('.modal-body').after("<div class=\"modal-footer\"><button data-bb-handler=\"ok\" type=\"button\" class=\"btn btn-primary\">OK</button></div>");
            } else {
                dialog.find('.modal-title').html('错误');
                dialog.find('.modal-body').html(res.msg);
                dialog.find('.modal-body').after("<div class=\"modal-footer\"><button data-bb-handler=\"ok\" type=\"button\" class=\"btn btn-primary\">OK</button></div>");

            }
        },
        error: function () {
            dialog.find('.modal-title').html('失败');
            dialog.find('.modal-body').html("导入失败, 请稍后重试");
            dialog.find('.modal-body').after("<div class=\"modal-footer\"><button data-bb-handler=\"ok\" type=\"button\" class=\"btn btn-primary\">OK</button></div>");
        }

    });
}